/*!
 * Copyright (c) 2023-present StarDreamNet
 */
(document.loader || (document.loader = [])).push(["index", class {
    constructor() { };
    dateSpanString(date1, date2) {
        // 获取两个日期的毫秒数
        var date1 = new Date(date1).getTime();
        var date2 = new Date(date2).getTime();

        // 计算两个日期的差值，以秒为单位
        var span = Math.abs(date2 - date1) / 1000;

        // 根据差值，判断时间差
        if (span < 60) {
            return "刚刚";
        } else if (span < 3600) {
            return Math.floor(span / 60) + "分钟前";
        } else if (span < 86400) {
            return Math.floor(span / 3600) + "小时前";
        } else if (span < 2592000) {
            return Math.floor(span / 86400) + "天前";
        } else if (span < 31104000) {
            return Math.floor(span / 2592000) + "个月前";
        } else {
            return Math.floor(span / 31104000) + "年前";
        }
    };

    resize() {
        $(".desktop").removeClass("fixed")
        if ($(document.documentElement).prop("scrollHeight") - $(window).height() <= 0) {
            $(".desktop").addClass("fixed")
        } else {
            $(".desktop").removeClass("fixed")
        }
    };

    pushStateWithSearchParams(data) {
        var url = new URL(location.href);
        for (let key in data) {
            if (data[key]) {
                url.searchParams.set(key, data[key]);
            } else {
                url.searchParams.delete(key);
            }
        }
        history.pushState({}, "", url.search);
    };

    initMobile() {
        if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            $(".app").addClass("mobile")
        }
    };

    initSW() {
        if (typeof navigator.serviceWorker == "undefined") return;
        navigator.serviceWorker.register("/sw.js").then(registration => {

            // 监听 sw 发现更新
            registration.addEventListener('updatefound', () => {

                const installingWorker = registration.installing;

                // 监听 安装状态更改
                installingWorker.addEventListener('statechange', () => {

                    // 如果是 安装完成 状态
                    if (installingWorker.state === 'installed') {
                        if (navigator.serviceWorker.controller) {

                            swal({
                                icon: "success",
                                title: "发现新版本",
                                text: "是否重新加载网页以获取更新？",
                                buttons: ['取消', '确认']
                            }).then(v => {
                                if (v) {
                                    // 进行更新操作
                                    if (registration.waiting) {
                                        registration.waiting.postMessage({ type: 'SKIP_WAITING' });
                                    }
                                }
                            });
                        }
                    }
                });
            })
        })

        // 如sw有更新，则重新加载网页
        let refreshing = false;
        navigator.serviceWorker.addEventListener('controllerchange', () => {
            if (refreshing) return;
            window.location.reload();
            refreshing = true;
        });

        // // 删除以前的sw
        // navigator.serviceWorker.getRegistrations().then(function (registrations) {
        //     for (let registration of registrations) {
        //         if (registration.active.scriptURL.includes("/sw.js"))
        //             registration.unregister();

        //     }
        // });
    };
    initSwalSimple() {
        if (typeof swal == 'undefined') return;

        Object.assign(swal, {
            skip(config) {
                config = config || {};

                var num = (config.num || 3);

                function upd() {
                    $(".swal-text").text(`将在 ${num || 0}${config.unit || "s"} 后跳转到 ${config.to || "首页"}`)
                }
                function to() {
                    location.href = config.src || "/";
                }

                swal({
                    icon: config.icon || "success",
                    title: config.title || "成功",
                    text: " ",
                    buttons: {
                        confirm: {
                            text: "立即跳转",
                            value: true,
                            visible: true,
                            className: "",
                            closeModal: true
                        }
                    },
                    closeOnClickOutside: false,
                }).then(v => {
                    if (v) {
                        to();
                    }
                });

                setInterval(() => {
                    num--;
                    upd();
                    if (num == 0) {
                        to();
                    }
                }, (config.mul || 1000));

                upd();
            },
        });
    };

    initHeaderUser() {
        $.ajax("/api/user/get_status?t=" + Date.now(), {
            contentType: 'application/json'
        }).done(function (data) {
            if (data.code == 200) {
                $(".app-header-user").attr("src", data.data.img)
                    .parent().attr("href", "/user/" + data.data.id);
            } else {
                $(".app-header-user").attr("src", "https://creation.codemao.cn/716/appcraft/IMAGE_U53LlVovA_1693015896678.png")
                    .parent().attr("href", "/login");
            }
        })
    }

    initMobile() {
        // 页头
        const nav = $('.app-header-nav')
        const mask = $('<div class="app-header-mask">')

        mask.insertAfter('.app-header-space').on('click', function () {
            mask.removeClass('show')
            nav.removeClass('show')
        })

        $('<div class="app-header-menu">').insertAfter('.app-header-space').on('click', function () {
            mask.addClass('show')
            nav.addClass('show')
        })

        // 底部导航栏
        const mnav = $('<div class="app-mobile-nav">')
        const mcfg = [
            [
                '/static/image/home.svg',
                '/',
                /^\/$/
            ],
            [
                '/static/image/sendpost.svg',
                '/shequ/sendpost',
                /^\/shequ\/sendpost$/
            ],
            [
                '/static/image/me.svg',
                () => $('header.app-header>a:has(.app-header-user)').attr('href'),
                /^\/user\/.+$/
            ]
        ]

        for (let item of mcfg) {
            let el = $('<img class="app-mobile-nav-item">');
            el.attr('src', item[0]);
            if (item[2].test(location.pathname)) el.addClass('active');
            el.on('click', function () {
                const url = typeof item[1] == 'function' ? item[1]() : item[1];
                const a = $('<a>');
                a.attr('href', url)
                a[0].click();
            })
            mnav.append(el);
        }

        mnav.appendTo('.app');
    }

    renderNameAndGroups(name, groups, url) {
        const main = $('<div class="app-user-nandg">');
        $('<a>').attr('href', url).text(name).appendTo(main);
        for (let group of groups) {
            $('<span>').text(group.title).appendTo(main);
        }
        return main;
    }

    init_(require) {
        this.initSW();
        this.resize();
        this.initMobile();
        this.initSwalSimple();
        this.initHeaderUser();
        $(window).on("resize", this.resize);
    };
}]);

// Modules Loader
!function () {
    if (typeof $ == "undefined") return document.body.innerText = "Modules loading failed.";
    $(document).ready(function () {
        const modules = new Map();
        const require = name => {
            var module = modules.get(name);
            return module || null;
        };
        const addModule = (name, content) => {
            if (modules.has(name)) {
                throw Error("The Module name" + String(name) + " has been named.");
            } else {
                try {
                    modules.set(name, content);
                } catch (e) {
                    throw Error("Module " + String(name) + " failed to load.\n" + e);
                }
            }
        };
        (document.loader || (document.loader = [])).forEach(module => {
            try {
                var name = module[0];
                var content = module[1];
                if (typeof content === 'function') {
                    if (content.prototype && content.prototype.constructor && content.prototype.constructor.toString().startsWith('class')) {
                        var x = new content();
                        addModule(name, x);
                        x.init_(require);
                    } else {
                        var exp = null;
                        var mod = { exports: exp }
                        content(require, exp, mod);
                        addModule(name, exp || mod.exports);
                    }
                } else if (typeof content === 'object') {
                    addModule(name, content);
                    content.init_(require);
                } else {
                    addModule(name, content);
                }
            } catch (e) {
                throw Error("Module " + String(name) + " failed to load.\n" + e);
            }
        });
    });
}();